import { useStore } from 'vuex';
import { computed } from 'vue';
// 购物车相关逻辑
export const useCommonCartEffect = (shopId) => {
  const store = useStore();
  const cartList = store.state.cartList;
  const changeCartItemInfo = (shopId, productId, productInfo, num) => {
    store.commit('changeCartItemInfo', { shopId, productId, productInfo, num });
    // console.log(shopId, productId, productInfo);
  };
  // 计算--购物车列表
  const shopList = computed(() => {
    const productList = cartList[shopId]?.productList || {};
    // const notEmptyProductList = {};
    // for (const key in productList) {
    //   const product = productList[key];
    //   if (product.count > 0) {
    //     notEmptyProductList[key] = product;
    //   }
    // }
    // console.log(notEmptyProductList);
    // return notEmptyProductList;
    return productList;
  });
  // 计算--商品名称
  const shopName = computed(() => {
    const productList = cartList[shopId]?.shopName || '';
    return productList;
  });
  // 计算--总价
  const totalPrice = computed(() => {
    const productList = cartList[shopId]?.productList;
    let price = 0;
    if (productList) {
      for (const i in productList) {
        const product = productList[i];
        if (product.check) {
          price += product.count * product.price;
        }
      }
    }
    return price.toFixed(2);
  });
  return { cartList, shopList, shopName, totalPrice, changeCartItemInfo };
};
